package com.you.springcloud.alibaba.demo.service.impl;

import com.you.springcloud.alibaba.demo.api.ServiceA;
import com.you.springcloud.alibaba.demo.dao.MemberDao;
import com.you.springcloud.alibaba.demo.dao.UserDao;
import com.you.springcloud.alibaba.demo.bo.UserBo;
import com.you.springcloud.alibaba.demo.entity.Member;
import com.you.springcloud.alibaba.demo.entity.User;
import com.you.springcloud.alibaba.demo.service.IMemberService;
import com.you.springcloud.alibaba.demo.vo.UserVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service(
        version = "1.0.0",
        interfaceClass = ServiceA.class,
        cluster = "failfast",
        loadbalance = "roundrobin",
        timeout = 6000
)
public class ServiceAImpl implements ServiceA {

    @Autowired
    private UserDao userDao;

    @Autowired
    private IMemberService memberService;

    public String greet(String name) {
        return "hello, " + name;
    }

    @Transactional
    @Override
    public String addUser(UserVo userVo) {
        if (userVo == null) {
            return "user is null!";
        }
        try {
            //模式超时时间
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        User user = new User();
        BeanUtils.copyProperties(userVo, user);
        int rows = userDao.insertUser(user);
        //插入会员表
        Member member = new Member();
        member.setId(userVo.getId());
        member.setName(userVo.getName());
        try {
            rows = memberService.saveMember(member);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "insert " + rows + " numbers!";
    }

    public List<UserVo> findUserById(String id) {
        System.out.println("----------call findUserById method----------");
        List<User> users = userDao.getUserById(id);
        List<UserVo> userVos = new ArrayList<UserVo>();
        BeanUtils.copyProperties(users, users);
        return userVos;
    }
}
